package com.example.pt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.dto.CommentDTO;
import com.example.pt.entity.Comment;
import com.example.pt.entity.User;
import com.example.pt.service.CommentService;
import com.example.pt.service.UserService;
import com.example.pt.utils.DownloadUrlUtils;
import com.example.pt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 评论控制器
 */
@RestController
@RequestMapping("/api/comments")
@CrossOrigin(origins = "*")
public class  CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;

    /**
     * 获取种子的评论列表
     * @param torrentId 种子ID
     * @param torrentId 种子ID
     * @param headers 请求头
     * @return 评论列表
     */
    @GetMapping("/torrent/{torrentId}")
    public ResponseEntity<?> getCommentsByTorrentId(
            @PathVariable Integer torrentId,
            @RequestHeader Map<String, String> headers) {
        
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 获取评论列表
            List<CommentDTO> comments = commentService.getCommentsByTorrentId(torrentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("comments", comments);
            response.put("total", comments.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "获取评论失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 添加评论
     * @param requestBody 请求体
     * @param headers 请求头
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<?> addComment(
            @RequestBody Map<String, Object> requestBody,
            @RequestHeader Map<String, String> headers) {
        
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token == null) {
                token = headers.get("authorization");
                if (token != null && token.startsWith("Bearer ")) {
                    token = token.substring(7);
                }
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 获取请求参数
            Integer torrentId = Integer.valueOf(requestBody.get("torrentId").toString());
            String content = requestBody.get("content").toString();
            Integer parentId = null;
            
            if (requestBody.containsKey("parentId") && requestBody.get("parentId") != null) {
                parentId = Integer.valueOf(requestBody.get("parentId").toString());
            }
            
            // 添加评论
            CommentDTO comment = commentService.addComment(torrentId, userId, content, parentId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "评论成功");
            response.put("comment", comment);
            
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (IllegalArgumentException e) {
            // 处理用户等级不足等参数错误
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", e.getMessage());
            
            // 返回403 Forbidden状态码，表示权限不足
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "评论失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 点赞评论
     * @param commentId 评论ID
     * @param headers 请求头
     * @return 点赞结果
     */
    @PostMapping("/{commentId}/like")
    public ResponseEntity<?> likeComment(
            @PathVariable Integer commentId,
            @RequestHeader Map<String, String> headers) {
        
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 点赞评论
            boolean success = commentService.likeComment(commentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("status", "success");
                response.put("message", "点赞成功");
            } else {
                response.put("status", "error");
                response.put("message", "点赞失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "点赞失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 取消点赞
     * @param commentId 评论ID
     * @param headers 请求头
     * @return 取消点赞结果
     */
    @PostMapping("/{commentId}/unlike")
    public ResponseEntity<?> unlikeComment(
            @PathVariable Integer commentId,
            @RequestHeader Map<String, String> headers) {
        
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 取消点赞
            boolean success = commentService.unlikeComment(commentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("status", "success");
                response.put("message", "取消点赞成功");
            } else {
                response.put("status", "error");
                response.put("message", "取消点赞失败");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "取消点赞失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 删除评论
     * @param commentId 评论ID
     * @param headers 请求头
     * @return 删除结果
     */
    @DeleteMapping("/{commentId}")
    public ResponseEntity<?> deleteComment(
            @PathVariable Integer commentId,
            @RequestHeader Map<String, String> headers) {
        
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 删除评论
            boolean success = commentService.deleteComment(commentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("status", "success");
                response.put("message", "删除评论成功，同时删除了所有相关回复");
            } else {
                response.put("status", "error");
                response.put("message", "删除评论失败，您可能没有权限");
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "删除评论失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    @GetMapping("/relatedInfo")
    public ResponseEntity<?> getRelatedInfo(@RequestHeader Map<String, String> header,
                                            @RequestParam Integer userId) {
        String token = header.get("token");
        try{
            JWTUtil.verifyToken(token);
        }catch (Exception e){
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录权限已失效！");
            response.put("status", "fail");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }

        if(userService.searchByUid(userId) != null){
            List<Comment> commentList = commentService.searchCommentsByUid(userId);
            if(commentList.size() == 0){
                Map<String, Object> response = new HashMap<>();
                response.put("status", "success");
                response.put("message", "用户所属评论为空！");
                return ResponseEntity.ok(response);
            }
            Map<String, Object> response = new HashMap<>();
            List<Map<String, Object>> comments = new ArrayList<>();
            for(Comment comment : commentList){
                Map<String, Object> commentMap = new HashMap<>();
                if(comment.getParentId() == null){
                    commentMap.put("commentId", comment.getCommentId());
                    commentMap.put("userId", comment.getUserId());
                    commentMap.put("content", comment.getContent());
                    commentMap.put("torrentId", comment.getTorrentId());
                    commentMap.put("replies", commentService.getReplyCommentsByCommentId(comment.getCommentId()));

                    comments.add(commentMap);
                }

            }
            response.put("status", "success");
            response.put("message", "查询成功！");
            response.put("comments", comments);
            return ResponseEntity.ok(response);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("status", "fail");
        response.put("message", "查询失败,userId不存在！");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);

    }

    @GetMapping("/getLike")
    public ResponseEntity<?> getLike(@RequestHeader Map<String, String > header,
                                     @RequestParam Integer userId) {
        String token = header.get("token");
        try{
            JWTUtil.verifyToken(token);
        }catch (Exception e){
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录权限已失效！");
            response.put("status", "fail");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }
        if(userService.searchByUid(userId) != null){
            List<Comment> commentList = commentService.searchCommentsByUid(userId);
            if(commentList.size() == 0){
                Map<String, Object> response = new HashMap<>();
                response.put("status", "success");
                response.put("message", "您还未发表过评论！");
                return ResponseEntity.ok(response);
            }
            List<Map<String, Object>> likeRecords = new ArrayList<>();

            for (Comment comment : commentList) {
                // 获取已排序的点赞用户ID列表
                List<Integer> userIds = commentService.getLikeUserIds(comment.getCommentId());

                for (Integer uid : userIds) {
                    User user = userService.searchByUid(uid);
                    if (user != null) {
                        // 获取点赞时间（假设通过commentId和userId可以查询点赞记录）
                        Date likeRecord = commentService.getCreateTime(comment.getCommentId(), uid);

                        Map<String, Object> record = new HashMap<>();
                        record.put("commentId", comment.getCommentId());
                        record.put("userId", uid);
                        record.put("username", user.getUsername());

                        String headshotUrl = downloadUrlUtils.generateDownloadLink(uid);

                        record.put("headshot",headshotUrl);

                        // 如果有点赞记录，添加创建时间
                        if (likeRecord != null) {
                            record.put("createTime", likeRecord);
                        } else {
                            // 没有记录时可以添加默认值或null
                            record.put("createTime", null);
                        }

                        likeRecords.add(record);
                    }
                }
            }

            if (likeRecords.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("status", "success");
                response.put("message", "您的评论暂时没人点赞");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("status", "success");
                response.put("likeRecords", likeRecords);
                return ResponseEntity.ok(response);
            }
        }

        Map<String, Object> response = new HashMap<>();
        response.put("status", "fail");
        response.put("message", "用户不存在，查询失败请联系管理员！");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
    }

    /**
     * 获取用户收到的点赞信息
     * @param headers 请求头
     * @return 点赞信息列表
     */
    @GetMapping("/received-likes")
    public ResponseEntity<?> getReceivedLikes(@RequestHeader Map<String, String> headers) {
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 获取用户收到的点赞信息
            List<Map<String, Object>> receivedLikes = commentService.getUserReceivedLikes(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("likes", receivedLikes);
            response.put("total", receivedLikes.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "获取点赞信息失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 获取用户评论收到的回复
     * @param headers 请求头
     * @return 回复信息列表
     */
    @GetMapping("/received-replies")
    public ResponseEntity<?> getReceivedReplies(@RequestHeader Map<String, String> headers) {
        try {
            // 验证Token并获取用户ID
            String token = headers.get("token");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 获取用户评论收到的回复
            List<Map<String, Object>> receivedReplies = commentService.getUserReceivedReplies(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("replies", receivedReplies);
            response.put("total", receivedReplies.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "获取回复信息失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
}
